package com.maxjay.common.exception.processor;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.UndeclaredThrowableException;
import java.sql.SQLException;

import org.hibernate.exception.GenericJDBCException;
import org.springframework.transaction.CannotCreateTransactionException;

import com.maxjay.common.exception.ERR;
import com.maxjay.common.exception.GeneException;

/**
 * 常见异常转换
 * @author zmw
 *
 */
public class OtherExceptionProcessor {
	public static Exception convertException(Exception ex) {
		if (ex instanceof NullPointerException) {
			return GeneException.getGeneException(ERR.EX_NULL_POINT, ex);
		} else if (ex instanceof UndeclaredThrowableException) {
			Throwable t = ((UndeclaredThrowableException) ex).getCause();
			if (t instanceof InvocationTargetException) {
				return OtherExceptionProcessor.convertException((InvocationTargetException) t);
			}
		} else if (ex instanceof InvocationTargetException) {
			Throwable t = ((InvocationTargetException) ex).getTargetException();
			if (t instanceof GeneException) {
				return (GeneException) t;
			}
		} else if (ex instanceof CannotCreateTransactionException) {
			Throwable t = ex.getCause();
			if (t instanceof GenericJDBCException) {
				return OtherExceptionProcessor.convertException((GenericJDBCException) t);
			}
		} else if (ex instanceof GenericJDBCException) {
			Throwable t = ex.getCause();
			if (t instanceof SQLException) {
				return GeneException.getGeneException((SQLException) t);
			}
		}
		// TODO 其他等待扩充
		return ex;
	}
}
